package moonhy.c2dm_client;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import moonhy.c2dm_client.R;
import moonhy.c2dm_client.R.anim;
import moonhy.c2dm_client.R.id;
import moonhy.c2dm_client.R.layout;
import moonhy.c2dm_client.R.string;
import moonhy.c2dm_client.dw.AccountData;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.LinearLayout.LayoutParams;

public class AccountActivity_bak extends Activity implements View.OnTouchListener{
	ViewFlipper flipper;
	TextView dateView;
	
	float xAtDown;
	float xAtUp;
	
	int year;
	int temp_month;
	
	final int BACKWORD = -9;
	final int FORWORD = 9;
	
	int viewIdxFirst = -1;
	int viewIdxLast = 1;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		/*
		super.onCreate(savedInstanceState);
        setContentView(R.layout.account_result);
        
        flipper = (ViewFlipper)findViewById(R.id.viewFlipper);
        flipper.setOnTouchListener(this);
        
        
        GregorianCalendar today = new GregorianCalendar();

        year = today.get ( today.YEAR );
        temp_month = today.get ( today.MONTH ) + 1;
        String month = (temp_month < 10 ? ("0"+temp_month) : Integer.toString(temp_month));
*/
        /*dateView = (TextView)findViewById(R.id.DateView);
        dateView.setText(Integer.toString(year) + "년 " + temp_month+"월");*/
        
		/*
        new initPage(this, Integer.toString(year), month, 0).execute();
        getDateDiff("prev");
        month = (temp_month < 10 ? ("0"+temp_month) : Integer.toString(temp_month));
        new initPage(this, Integer.toString(year), month, BACKWORD).execute();
        viewIdxFirst--;
        getDateDiff("next");
        month = (temp_month < 10 ? ("0"+temp_month) : Integer.toString(temp_month));
        new initPage(this, Integer.toString(year), month, FORWORD).execute();
        viewIdxLast++;
        */
        /*
        TextView tv = new TextView(this);
        tv.setText("View 4\nDynamically added");
        tv.setTextColor(Color.CYAN);
        flipper.addView(tv);
		*/
		//new initPage(this).execute();
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		float pressDownPoint = 0;
		int flipperViewCount = flipper.getChildCount();
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		// will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH
		int screenDensity = dm.densityDpi;
		int screenWidth = dm.widthPixels;
		
		screenDensity = 10;

		/*
		switch (event.getAction())
	    {
	        case MotionEvent.ACTION_DOWN:
	        {
	            //Gets the startpoint for you finger
	            pressDownPoint = event.getX();
	            
	            
	            //Gets how many view there is in the viewflipper
	            flipperViewCount = flipper.getChildCount();

	            //Checks if there is a view to the left of the current view
	            //if there is, it positions it to the left of the current view
	            if (flipper.getDisplayedChild() > 0)
	            {
	                View leftChild = flipper.getChildAt(flipper.getDisplayedChild() - 1);
	                //You must set the left view to invisible or visible 
	                //or it will not move to the position you tell it
	                leftChild.setVisibility(View.INVISIBLE);
	                leftChild.layout(-screenWidth, 
	                        leftChild.getTop(), 0, 
	                        leftChild.getBottom());
	            }

	            //Same as above but for the view to the right
	            if (flipper.getDisplayedChild() < flipperViewCount - 1)
	            {
	                View rightChild = flipper.getChildAt(flipper.getDisplayedChild() + 1);
	                rightChild.setVisibility(View.INVISIBLE);
	                rightChild.layout(screenWidth, rightChild.getTop(), screenWidth * 2, 
	                        rightChild.getBottom());
	            }
	            break;
	        }
	        case MotionEvent.ACTION_UP:
	        {
	            //Gets the absolute position on the screen
	            float releasePoint = event.getRawX();

	            //Calculates if the fling is to the right or left
	//The screenDensity variable is simply the density of the device
	//Have in mind that this will not flipp the viewflipper if you drag
	//your finger less than about 0.5cm (depeding on the device)
	//In that case you need to make an animation that takes the view back
	//to its original position. Else it will just get stuck where you
	//let go with your finger.
	            //if (Math.abs(pressDownPoint - releasePoint) / screenDensity > 30){
	                if (pressDownPoint > releasePoint){
	                	flipper.setInAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_left_in));
	    		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_left_out));
	                    flipper.showNext();
	                }else{
	                	flipper.setInAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_right_in));
	    		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
	    		        		R.anim.push_right_out));
	                    flipper.showPrevious();
	                }
	            //}
	            break;
	        }
	        case MotionEvent.ACTION_MOVE:
	        {
	            View currentView = flipper.getCurrentView();

	            //Moves the current view
				//screenWidth is based on the current devices screen width
	            currentView.layout((int)(event.getRawX() - pressDownPoint), 
	                    currentView.getTop(), (int)(event.getRawX() - pressDownPoint) + screenWidth, 
	                    currentView.getBottom());

	            //Moves the view to the left if there is one
	            if (flipper.getDisplayedChild() > 0)
	            {
	                View leftChild = flipper.getChildAt(flipper.getDisplayedChild() - 1);
	                leftChild.layout((int)(event.getRawX() - pressDownPoint - screenWidth), 
	                        leftChild.getTop(), (int)(event.getRawX() - pressDownPoint), 
	                        leftChild.getBottom());

	                //Sets the left view to visible so it shows
	                if (leftChild.getVisibility() == View.INVISIBLE)
	                {
	                    leftChild.setVisibility(View.VISIBLE);
	                }
	            }

	            //Same as above but for the view to the right
	            if (flipper.getDisplayedChild() < flipperViewCount - 1)
	            {
	                View rightChild = flipper.getChildAt(flipper.getDisplayedChild() + 1);
	                rightChild.layout((int)(event.getRawX() - pressDownPoint + screenWidth), 
	                        rightChild.getTop(), (int)(event.getRawX() - pressDownPoint + (screenWidth * 2)), 
	                        rightChild.getBottom());

	                if (rightChild.getVisibility() == View.INVISIBLE)
	                {
	                    rightChild.setVisibility(View.VISIBLE);
	                }
	            }
	        }

	    }
		*/
		
		if(v != flipper) return false;
		
		if(event.getAction() == MotionEvent.ACTION_DOWN) {
			xAtDown = event.getX();
		}else if(event.getAction() == MotionEvent.ACTION_MOVE){
			///Log.d("C2DM", "ddddddd:   " + event.getX());
			if( event.getX() < xAtDown ) {
				flipper.setInAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_in));
		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_out));
			}
		}else if(event.getAction() == MotionEvent.ACTION_UP){
			xAtUp = event.getX();
						
			if( xAtUp < xAtDown ) {
				flipper.setInAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_in));
		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_left_out));
		        		
				flipper.showNext();
				
				getDateDiff("next");
		        String month = (temp_month < 10 ? ("0"+temp_month) : Integer.toString(temp_month));
		        new initPage(this, Integer.toString(year), month, FORWORD).execute();
		        viewIdxLast++;
			}
			else if (xAtUp > xAtDown){
				flipper.setInAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_right_in));
		        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
		        		R.anim.push_right_out));
		        
				flipper.showPrevious();
				
				getDateDiff("prev");
				String month = (temp_month < 10 ? ("0"+temp_month) : Integer.toString(temp_month));
		        new initPage(this, Integer.toString(year), month, BACKWORD).execute();
		        viewIdxFirst--;
			}
		}
			
		return true;
	}
	
	private void getDateDiff(String ck){
		int cYear = year;
		int cMonth = temp_month;
		
		if(ck.equals("next")){
			if(cMonth == 12){
				cMonth = 1;
				cYear++;
			}else{
				cMonth++;
			}
		}else{
			if(cMonth == 1){
				cMonth = 12;
				cYear--;
			}else{
				cMonth--;
			}
		}
		
		//Log.d("C2DM", "yy: " + cYear + "  mm" + cMonth);
		year = cYear;
		temp_month = cMonth;
		
	}
	
	private ArrayList<AccountData> setData(Context context, String frm_year, String frm_month){
		//String readNotice = readJSON("http://moonhy.mireene.com/kline/notice/notice_list.php");
		ArrayList<AccountData> md_array = new ArrayList<AccountData>();
		try {
			httpConnectionManager hcm = new httpConnectionManager(context);
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("frm_year", frm_year);
		    map.put("frm_month", frm_month);

			
			JSONObject json = new JSONObject(hcm.readJSON(getString(R.string.SERVER_URL) + "info/service_account.php", map));
			
			JSONObject json_header = json.getJSONObject("header");
			JSONArray json_result = json.getJSONArray("data_result");
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				AccountData tmp_nd = new AccountData();
				tmp_nd.setAccTitle(jsonObject.getString("KMA_TITLE"));
				tmp_nd.setAccIn(jsonObject.getString("KMA_IN"));
				tmp_nd.setAccOut(jsonObject.getString("KMA_OUT"));
				md_array.add(i, tmp_nd);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return md_array;
	}
		
	private class initPage extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener{
		ArrayList<AccountData> md_array;
		private ProgressDialog dialog;
		private Context context;
		private String frm_year;
		private String frm_month;
		private int order;
		
		private initPage(Context context, String frm_year, String frm_month, int order){
			this.context = context;
			this.frm_year = frm_year;
			this.frm_month = frm_month;
			this.order = order;
			
			Log.d("C2DM", "year:" + frm_year + "  month: " + frm_month + "  order: " + order);
		}

		protected void onPreExecute(){
			dialog = ProgressDialog.show(AccountActivity_bak.this, "", "Loading. Please wait...", true);
		}

		protected Void doInBackground(Void... unused){
			md_array = setData(context, frm_year, frm_month);
    		return null;
        }

        protected void onPostExecute(Void unused)
        {
            dialog.dismiss();
            
            TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
            TableRow.LayoutParams cellLp = new TableRow.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
            
            
            TableLayout table	= new TableLayout(context);
            
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            table.setLayoutParams(lp);
            
            TableRow trDate		= new TableRow(context);
            
            TextView tdDate	= new TextView(context);
            tdDate.setText(frm_year + "년 " + frm_month + "월");
            tdDate.setGravity(Gravity.CENTER);
            tdDate.setTextColor(0xFFFFFFFF);
            tdDate.setBackgroundColor(0xFFD34937);
            tdDate.setPadding(20, 10, 20, 10);
            
            trDate.addView(tdDate, cellLp);
            table.addView(trDate, rowLp);
            
            
            TableRow trTop		= new TableRow(context);
            
            TextView tdTop		= new TextView(context);
            tdTop.setText("항목");
            tdTop.setGravity(Gravity.CENTER);
            tdTop.setTextColor(0xFFFFFFFF);
            tdTop.setBackgroundColor(0xFF787974);
            tdTop.setPadding(20, 10, 20, 10);
            
            TextView td2Top	= new TextView(context);
            td2Top.setText("수입");
            td2Top.setGravity(Gravity.CENTER);
            td2Top.setTextColor(0xFFFFFFFF);
            td2Top.setBackgroundColor(0xFF787974);
            td2Top.setPadding(20, 10, 20, 10);
            
            TextView td3Top	= new TextView(context);
            td3Top.setText("지출");
            td3Top.setGravity(Gravity.CENTER);
            td3Top.setTextColor(0xFFFFFFFF);
            td3Top.setBackgroundColor(0xFF787974);
            td3Top.setPadding(20, 10, 20, 10);
            
            
            
            trTop.addView(tdTop, cellLp);
            trTop.addView(td2Top, cellLp);
            trTop.addView(td3Top, cellLp);

            table.addView(trTop, rowLp);
            
            
            int bgColor = 0xFFFFFFFF;
            for(int i = 0 ; i < md_array.size(); i++){
            	
            	if(i % 2 == 0){
            		bgColor = 0xFFE7EBEE;
            	}else{
            		bgColor = 0xFFFFFFFF;
            	}
    	        TableRow tr		= new TableRow(context);
    	        
    	        TextView td		= new TextView(context);
    	        td.setText(md_array.get(i).getAccTitle());
    	        td.setGravity(Gravity.CENTER);
    	        td.setTextColor(0xFF515151);
    	        td.setBackgroundColor(bgColor);
    	        td.setPadding(10, 10, 5, 10);
    	        
    	        TextView td2	= new TextView(context);
    	        td2.setText(md_array.get(i).getAccIn());
    	        td2.setGravity(Gravity.CENTER);
    	        td2.setTextColor(0xFF515151);
    	        td2.setBackgroundColor(bgColor);
    	        td2.setPadding(10, 10, 5, 10);
    	        
    	        TextView td3	= new TextView(context);
    	        td3.setText(md_array.get(i).getAccOut());
    	        td3.setGravity(Gravity.CENTER);
    	        td3.setTextColor(0xFF515151);
    	        td3.setBackgroundColor(bgColor);
    	        td3.setPadding(10, 10, 5, 10);
    	        
    	        tr.addView(td, cellLp);
    	        tr.addView(td2, cellLp);
    	        tr.addView(td3, cellLp);
    	
    	        table.addView(tr, rowLp);
            }
            
            if(order == BACKWORD){
            	flipper.addView(table, viewIdxFirst);
            }else if(order == FORWORD){
            	flipper.addView(table, viewIdxLast);
            }else{
            	flipper.addView(table, 0);
            }
            
        }

        public void onCancel(DialogInterface dialog)
        {
        	cancel(true);
        	dialog.dismiss();
        }
	}
}
